//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package roadmap_dao

import (
	"context"
	"fmt"

	"atomgit.com/openlinksaas-org/api-server/dao/db_ns"
	"atomgit.com/openlinksaas-org/proto-gen-go.git/roadmap_user_api"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

type AccessRecordDbItem struct {
	RecordId           string `bson:"_id"` //自动生成
	RoadmapId          string `bson:"roadmapId"`
	UserId             string `bson:"userId"`
	TimeStamp          int64  `bson:"timeStamp"`
	DoneTopicCount     uint32 `bson:"doneTopicCount"`
	TotalTopicCount    uint32 `bson:"totalTopicCount"`
	DoneSubTopicCount  uint32 `bson:"doneSubTopicCount"`
	TotalSubTopicCount uint32 `bson:"totalSubTopicCount"`
}

func (item *AccessRecordDbItem) ToAccessRecord() *roadmap_user_api.AccessRecord {
	return &roadmap_user_api.AccessRecord{
		RoadmapId:          item.RoadmapId,
		UserId:             item.UserId,
		TimeStamp:          item.TimeStamp,
		DoneTopicCount:     item.DoneTopicCount,
		TotalTopicCount:    item.TotalTopicCount,
		DoneSubTopicCount:  item.DoneSubTopicCount,
		TotalSubTopicCount: item.TotalSubTopicCount,
	}
}

type _AccessRecordDao struct {
	mc *mongo.Collection
}

func newAccessRecordDao(db *mongo.Database) (*_AccessRecordDao, error) {
	mc := db.Collection(db_ns.DB_NS_ROADMAP + "access_record")
	_, err := mc.Indexes().CreateMany(context.Background(), []mongo.IndexModel{
		{
			Keys: bson.D{{"roadmapId", 1}},
		},
		{
			Keys: bson.D{{"userId", 1}, {"timeStamp", 1}},
		},
	})
	if err != nil {
		return nil, err
	}
	return &_AccessRecordDao{mc: mc}, nil
}

func (db *_AccessRecordDao) Upsert(ctx context.Context, dbItem *AccessRecordDbItem) error {
	dbItem.RecordId = db.genRecordId(dbItem.UserId, dbItem.RoadmapId)
	_, err := db.mc.UpdateOne(ctx, bson.M{"_id": dbItem.RecordId}, bson.M{"$set": dbItem},
		options.Update().SetUpsert(true))
	return err
}

func (db *_AccessRecordDao) genRecordId(userId, roadmapId string) string {
	return fmt.Sprintf("%s:%s", userId, roadmapId)
}

func (db *_AccessRecordDao) Exist(ctx context.Context, userId, roadmapId string) (bool, error) {
	recordId := db.genRecordId(userId, roadmapId)
	count, err := db.mc.CountDocuments(ctx, bson.M{"_id": recordId})
	return count > 0, err
}

func (db *_AccessRecordDao) CountByUser(ctx context.Context, userId string) (uint32, error) {
	count, err := db.mc.CountDocuments(ctx, bson.M{"userId": userId})
	return uint32(count), err
}

func (db *_AccessRecordDao) ListByUser(ctx context.Context, userId string, offset, limit int64) ([]*AccessRecordDbItem, error) {
	cursor, err := db.mc.Find(ctx, bson.M{"userId": userId}, options.Find().SetSkip(offset).SetLimit(limit).SetSort(bson.M{"timeStamp": -1}))
	if err != nil {
		return nil, err
	}
	retList := []*AccessRecordDbItem{}
	err = cursor.All(ctx, &retList)
	return retList, err
}

func (db *_AccessRecordDao) Remove(ctx context.Context, userId, roadmapId string) error {
	recordId := db.genRecordId(userId, roadmapId)
	_, err := db.mc.DeleteOne(ctx, bson.M{"_id": recordId})
	return err
}

func (db *_AccessRecordDao) RemoveByRoadmap(ctx context.Context, roadmapId string) error {
	_, err := db.mc.DeleteMany(ctx, bson.M{"roadmapId": roadmapId})
	return err
}
